﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using RXY_Mall.Core;
using RXY_Mall.Data;
using RXY_Mall.Domain;
using System.Data.Entity;
using RXY_Mall.Application.User.Dto;
using RXY_Mall.Core.Tool;

namespace RXY_Mall.Application.User
{
    public class UserService : RXY_MallAppServiceBase, IUserService
    {
        public async Task<Response<bool>> AddUser(UserAddInput input)
        {
            Response<bool> result = new Response<bool>();
            try
            {
                var user = new gw_user()
                {
                    name = input.name,
                    add_time = DateTime.Now,
                    add_ip = DcRequest.GetIP(),
                    grade = 0,
                    sex = "M",
                    status = 1,
                    token = Guid.NewGuid().ToString(),
                };
                if (input.parent_id != 0)
                {
                    user.parent_id = input.parent_id;
                }
                db.gw_users.Add(user);

                gw_finance_property userProperty = new gw_finance_property()
                {
                    balance = 0,
                    bean = 0,
                    id = user.id,
                    child = 0,
                    exp = 0,
                };
                user.gw_finance_property = userProperty;

                await db.SaveChangesAsync();
                result.data = true;
                result.code = 1;
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog(ex);
                result.msg = ex.ToString();
                result.code = 2;
            }
            return result;
        }

        public IPagedList<UserList> GetUsersByPage(int iDisplayStart, int iDisplayLength, string dateMin, string dateMax, string userName, string userNo, int status, int grade, int isVip, out int totalCount)
        {
            iDisplayLength = iDisplayLength < 1 ? 10 : iDisplayLength;
            DateTime dtMin = DateTime.MinValue;
            DateTime dtMax = DateTime.MaxValue;

            var source = db.gw_users
                .Include(u => u.gw_company)
                .Include(u => u.gw_user_store)
                .Include(u => u.gw_finance_property)
                .Where(u => !u.deleted)
                .Select(u => new UserList()
                {
                    add_time = u.add_time,
                    balance = u.gw_finance_property.balance,
                    bean = u.gw_finance_property.bean,
                    company_name = u.gw_company.name,
                    exp = u.gw_finance_property.exp,
                    grade = u.grade,
                    id = u.id,
                    grade_name = "",
                    name = u.name,
                    nick_name = u.nick_name,
                    real_name = u.real_name,
                    status = u.status,
                    store_address = u.gw_user_store.area + u.gw_user_store.address,
                    store_name = u.gw_user_store.name,
                    store_type = ((StoreType)u.gw_user_store.type).ToString(),
                });
            if (status > -1)
            {
                source = source.Where(m => m.status == status);
            }
            if (grade > -1)
            {
                source = source.Where(m => m.grade == grade);
            }
            if (isVip > -1)
            {
                if (isVip == 1)
                {
                    source = source.Where(m => m.grade > 0);
                }
                else
                {
                    source = source.Where(m => m.grade == 0);
                }
            }
            if (!string.IsNullOrWhiteSpace(userName))
            {
                source = source.Where(m => m.name.Contains(userName));
            }
            if (!string.IsNullOrWhiteSpace(userNo) && Validator.IsInt(userNo))
            {
                int user_no = int.Parse(userNo);
                source = source.Where(m => m.id == user_no);
            }
            if (!string.IsNullOrWhiteSpace(dateMin))
            {
                dtMin = DateTime.Parse(dateMin);
            }
            if (!string.IsNullOrWhiteSpace(dateMax))
            {
                dtMax = DateTime.Parse(dateMax).Date.AddDays(1); ;
            }
            source = source.Where(m => m.add_time >= dtMin && m.add_time <= dtMax);
            source = source.OrderByDescending(s => s.add_time);
            var pagelist = new PagedList<UserList>(source, iDisplayStart / iDisplayLength + 1, iDisplayLength);

            totalCount = pagelist.TotalCount;

            return pagelist;
        }

        public Response<IPagedList<UserList>> GetUsersByPage(string date_start, string date_end, string user_name, string user_no, int status, int grade, int page_index = 1, int page_size = 20, int shop_id = -1)
        {
            DateTime dtMin = DateTime.MinValue;
            DateTime dtMax = DateTime.MaxValue;
            Response<IPagedList<UserList>> output = new Response<IPagedList<UserList>>();
            try
            {
                var source = db.gw_users
                .Include(u => u.gw_company)
                .Include(u => u.gw_user_store)
                .Include(u => u.gw_finance_property)
                .Where(u => !u.deleted)
                .Select(u => new UserList()
                {
                    add_time = u.add_time,
                    balance = u.gw_finance_property.balance,
                    bean = u.gw_finance_property.bean,
                    company_name = u.gw_company.name,
                    exp = u.gw_finance_property.exp,
                    grade = u.grade,
                    id = u.id,
                    grade_name = "",
                    name = u.name,
                    nick_name = u.nick_name,
                    real_name = u.real_name,
                    status = u.status,
                    store_address = u.gw_user_store.address,
                    store_area = u.gw_user_store.area,
                    store_name = u.gw_user_store.name,
                    store_type = ((StoreType)u.gw_user_store.type).ToString(),
                });
                if (status > -1)
                {
                    source = source.Where(m => m.status == status);
                }
                if (grade > -1)
                {
                    source = source.Where(m => m.grade == grade);
                }
                if (!string.IsNullOrWhiteSpace(user_name))
                {
                    source = source.Where(m => m.name.Contains(user_name));
                }
                if (!string.IsNullOrWhiteSpace(user_no) && Validator.IsInt(user_no))
                {
                    int user_id = int.Parse(user_no);
                    source = source.Where(m => m.id == user_id);
                }
                if (!string.IsNullOrWhiteSpace(date_start))
                {
                    dtMin = DateTime.Parse(date_start);
                }
                if (!string.IsNullOrWhiteSpace(date_end))
                {
                    dtMax = DateTime.Parse(date_end).Date.AddDays(1); ;
                }
                source = source.Where(m => m.add_time >= dtMin && m.add_time <= dtMax);
                source = source.OrderByDescending(s => s.add_time);
                var page_list = new PagedList<UserList>(source, page_index, page_size);
                output.code = 1;
                output.data = page_list;
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog(ex);
                output.code = 2;
                output.msg = ex.Message;
            }
            return output;
            
        }

        public bool SetUserPwd(int manageId, int userId, string newPassword)
        {
            LogHelper.WriteLog(String.Format("管理员{0}重置会员{1}登录密码为123456", manageId, userId));
            var entity = db.gw_user_passwords.FirstOrDefault(i => i.user_id == userId && i.type == 0);
            if (null != entity)
            {
                entity.password = SecureHelper.Get32Md5Str(newPassword, true);
                db.SaveChanges();
                return true;
            }
            else
                return false;
        }

        public bool SetIsUse(int manageId, int id, int isUse)
        {
            LogHelper.WriteLog(String.Format("管理员{0}操作用户{1}状态为{2}", manageId, id, isUse));
            var entity = db.gw_users.FirstOrDefault(i => i.id == id);
            if (null != entity)
            {
                entity.status = (byte)isUse;
                entity.token = "";
                db.SaveChanges();
                return true;
            }
            return false;
        }

        public async Task<bool> SetVip(int manageId, int id, int isVip)
        {
            LogHelper.WriteLog(String.Format("管理员{0}操作设置会员{1}状态为{2}", manageId, id, isVip));

            var entity = db.gw_users.FirstOrDefault(i => i.id == id);
            if (null != entity && entity.grade < 1)
            {
                var vip = new gw_order_member()
                {
                    order_no = "M00015" + DateTime.Now.ToString("yyMMddHHmmss") + RandomHelper.CreateRandomValue(6),
                    user_id = id,
                    buy_type = 3,
                    buy_year = 1,
                    pay_type = 5,
                    year_money = 0,
                    pay_no = "-",
                    pay_time = DateTime.Now,
                    status = 10,
                    add_time = DateTime.Now,
                    remark = "管理员设为趣卡会员，赠送1年会员",
                    amount = 0,
                };
                db.gw_order_members.Add(vip);
                await db.SaveChangesAsync();
                var pay = new gw_order_member_payment()
                {
                    id = vip.id,
                    pay_no = vip.id + "-",
                    pay_type = 5,
                    pay_amount = 0,
                    add_time = DateTime.Now,
                    remark = "管理员设为趣卡会员，赠送1年会员",
                };
                db.gw_order_member_payments.Add(pay);
                entity.start_time = DateTime.Now;
                entity.end_time = DateTime.Now.AddYears(1);
                entity.grade = 1;
                await db.SaveChangesAsync();
                LogHelper.WriteLog("管理员" + manageId + "操作：用户" + id + "设为趣卡会员");
                return true;
            }
            return false;
        }
    }
}
